﻿using System;
using System.Collections.Generic;
using Gencode.VECore.VectorShape;


namespace Gencode.VECore.History
{
    public class StateChangeCommand : Command
    {
        // Selected object(s) before operation
        List<VECShape> listBefore;

        // Selected object(s) after operation
        List<VECShape> listAfter;
        

        // Create this command BEFORE operation.
        public StateChangeCommand(ShapeList shapeList)
        {
            // Keep objects state before operation.
            FillList(shapeList, ref listBefore);
        }

        // Call this function AFTER operation.
        public void NewState(ShapeList shapeList)
        {
            // Keep objects state after operation.
            FillList(shapeList, ref listAfter);
        }

        public override void Undo(ShapeList shapeList)
        {
            // Replace all objects in the list with objects from listBefore
            ReplaceObjects(shapeList, listBefore);
        }

        public override void Redo(ShapeList shapeList)
        {
            // Replace all objects in the list with objects from listAfter
            ReplaceObjects(shapeList, listAfter);
        }

        // Replace objects in graphicsList with objects from list
        private void ReplaceObjects(ShapeList shapeList, List<VECShape> list)
        {
            for ( int i = 0; i < shapeList.Count; i++ )
            {
                VECShape replacement = null;

                foreach (VECShape shape in list)
                {
                    if ( shape.ID == shapeList[i].ID )
                    {
                        replacement = shape;
                        break;
                    }
                }

                if ( replacement != null )
                {
                    shapeList.Replace(i, replacement);
                }
            }
        }

        // Fill list from selection
        private void FillList(ShapeList shapeList, ref List<VECShape> listToFill)
        {
            listToFill = new List<VECShape>();

            foreach (VECShape shape in shapeList.Selection)
            {
                listToFill.Add(shape.Clone());
            }
        }
    }
}
